package edu.bbu.license.client.android.services.file.model;


public class ServerFile implements FileModel {
	
	public static final int FILE = 0;
	public static final int DIRECTORY = 1;
	public static final int FILE_VERSION = 2;
	private static final String SEPARATOR = "\\";
	private static final String EMPTY_NAME = "";

	private int type;
	private String name;
	private String path;
	private int version = -1;
	
	public ServerFile() {
		this(SEPARATOR, EMPTY_NAME, FILE);
	}
	
	public ServerFile(String path, String name, int type) {
		if(!path.endsWith(SEPARATOR)) {
			path = path + SEPARATOR;
		} 
			
		this.path = path;
		this.name = name;
		this.type = type;
	}
	
	public ServerFile(String path, String name, int version, int type) {
		this(path, name, type);
		this.version = version;
	}
	
	public String getRegularPath() {
		return path;
	}
	
	public String getRegularName() {
		return name;
	}
	
	@Override
	public ServerFile getAncestor() {
		int lastSeparatorIndex = path.substring(0, path.length() - 1).lastIndexOf(SEPARATOR);
		
		if(lastSeparatorIndex > 0) {
			String parrentPath = path.substring(0, lastSeparatorIndex);
			String parrentName = path.substring(lastSeparatorIndex + 1, path.length() - 1);
			
			return new ServerFile(parrentPath, parrentName, DIRECTORY);
		}
		
		return null;
	}

	@Override
	public ServerFile getSuccessor(String child) {
		return new ServerFile(path + name + SEPARATOR, child, DIRECTORY);
	}

	@Override
	public String getName() {
		if(isFileVersion()) {
			return Integer.toString(version);
		}
		
		return name;
	}

	@Override
	public String getAbsolutePath() {
		return path + name;
	}

	@Override
	public boolean isFile() {
		return type == FILE || type == FILE_VERSION;
	}

	@Override
	public boolean isDirectory() {
		return type == DIRECTORY;
	}
	
	public boolean isFileVersion() {
		return type == FILE_VERSION;
	}
	
	public int getVersion() {
		return version;
	}
}
